package com.tsu.mall.order.Controller;

import com.tsu.mall.common.VO.LayuiTableVO;
import com.tsu.mall.common.entity.Member;
import com.tsu.mall.common.service.IMemberService;
import com.tsu.mall.common.util.RequestUtil;
import com.tsu.mall.order.util.SendMsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/registration")
public class RegistrationController {
    @Autowired
    private IMemberService iMemberService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @GetMapping("/registrationPage")
    public String registration(){
        return "registration";
    }
    @PostMapping("/sendMsgCode")
    @ResponseBody
    public LayuiTableVO sendMsg(String phone) throws Exception{
        //判断此手机号是否注册过
        LayuiTableVO vo = new LayuiTableVO();
        Member member=iMemberService.selectPhoneById(phone);
        //随机生成六位随机数字验证码
        String code=randomString(6);
        if (member == null) {//没有注册过
            redisTemplate.opsForValue().set("reg-code-"+phone,code,5, TimeUnit.MINUTES);
            SendMsgUtil.sendMsg(phone,code);//发送验证码
        }else{
            vo.setCode(1);
            vo.setMsg("手机号已被注册过!");
        }
        return vo;
    }

    //生成验证码,随机生成字符串，可指定长度
    public String randomString(int length) {
        StringBuffer sb=new StringBuffer();
        for(int i=1;i<=length;i++) {
            sb.append(new Random().nextInt(10));
        }
        return sb.toString();
    }


    @PostMapping("/reg")
    @ResponseBody
    public LayuiTableVO reg(String code,String username,String phone,String password,String confirmPassword){
       return iMemberService.reg(code,username,phone,password,confirmPassword);
    }

}
